package com.gengzp.system.facade.impl;

import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.base.entity.GenericEntity;
import com.gengzp.common.model.base.resp.GenericResp;
import com.gengzp.common.model.user.entity.SysUser;
import com.gengzp.permission.utils.PermissionUtils;
import com.gengzp.system.facade.ISysUserFacade;
import com.gengzp.system.mapper.SysUserMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName SysUserFacadeImpl
 * @Description 系统用户门面层实现类
 * @Author gengzp
 * @Date 2025/5/17 2:09
 */
@Service
public class SysUserFacadeImpl implements ISysUserFacade {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser searchSysUserById(Long userId) {
        if (Objects.isNull(userId)) {
            throw BusinessException.get("用户id不能为空");
        }

        return sysUserMapper.selectSysUserById(userId);
    }

    @Override
    public List<SysUser> searchSysUserByUserAccountAndUserNickname(String userAccount, String userNickname) {
        if (StringUtils.isBlank(userAccount) && StringUtils.isBlank(userNickname)) {
            throw BusinessException.get("用户账号和用户昵称不能同时为空");
        }

        return sysUserMapper.selectSysUserByUserAccountOrUserNickname(userAccount, userNickname);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysUser(SysUser sysUser) {
        if (Objects.isNull(sysUser)) {
            throw BusinessException.get("用户信息不能为空");
        }
        sysUserMapper.insertSysUser(sysUser);
    }

    @Override
    public Map<Long, String> searchUserId2NicknameMapByUserIds(Collection<Long> userIds) {
        Map<Long, String> result = Maps.newHashMap();
        if (CollectionUtils.isEmpty(userIds)) {
            return result;
        }

        // 拼接超级管理员信息
        result.put(Long.valueOf(PermissionUtils.getSuperAdminUserId()), "超级管理员");

        // 根据id查询用户集合
        List<SysUser> sysUsers = sysUserMapper.selectSysUserByIds(Lists.newArrayList(userIds));
        if (CollectionUtils.isEmpty(sysUsers)) {
            return result;
        }

        // 用户id对应昵称映射   key:用户id    value:用户昵称
        Map<Long, String> map = sysUsers.stream().collect(Collectors.toMap(GenericEntity::getId, SysUser::getUserNickname));

        // 循环填充查询结果, 未查询到的用户昵称标注不存在
        userIds.forEach(v -> result.put(v, map.getOrDefault(v, "用户已不存在")));
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editSysUser(SysUser sysUser) {
        if (Objects.isNull(sysUser)) {
            throw BusinessException.get("用户信息不能为空");
        }

        sysUserMapper.updateSysUserById(sysUser);
    }

    @Override
    public void fillInEntitiesOperatorInfo(List<? extends GenericResp> entities) {
        if (CollectionUtils.isEmpty(entities)) {
            return;
        }

        // 根据所有出现过的操作人id查询操作人昵称映射
        Map<Long, String> operatorUserId2UserNicknameMap = searchUserId2NicknameMapByUserIds(
                entities.stream().map(v -> Lists.newArrayList(v.getCreatedBy(), v.getLastModifiedBy()))
                        .flatMap(Collection::stream).distinct().map(Long::valueOf).toList());

        // 循环填充操作人信息
        entities.forEach(v -> {
            v.setCreatedByUserNickname(operatorUserId2UserNicknameMap.get(Long.valueOf(v.getCreatedBy())));
            v.setLastModifiedByUserNickname(operatorUserId2UserNicknameMap.get(Long.valueOf(v.getLastModifiedBy())));
        });
    }

    @Override
    public void fillInEntityOperatorInfo(GenericResp entity) {
        if (Objects.isNull(entity)) {
            return;
        }

        // 获取操作人信息
        Map<Long, String> operatorUserId2UserNicknameMap = searchUserId2NicknameMapByUserIds(
                Lists.newArrayList(Long.valueOf(entity.getCreatedBy()), Long.valueOf(entity.getLastModifiedBy())));

        // 填充操作人信息
        entity.setCreatedByUserNickname(operatorUserId2UserNicknameMap.get(Long.valueOf(entity.getCreatedBy())));
        entity.setLastModifiedByUserNickname(operatorUserId2UserNicknameMap.get(Long.valueOf(entity.getLastModifiedBy())));
    }

}
